<?php
// 应用公共文件

/**
 * 成功数据格式输出
 * @param string $message
 * @param null $data
 * @return \think\response\Json
 */
function success($message = '', $data = null) {
    return json(['status' => 0, 'message' => $message, 'data' => $data]);
}

/**
 * 失败数据格式输出
 * @param string $message
 * @return \think\response\Json
 */
function fail($message = "") {
    return json(['status' => 1, 'message' => $message]);
}

/**
 * 获取客户端ip地址
 * @return bool
 */
function getIp(){
    $ip=false;
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ips=explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']);
        if($ip){
            array_unshift($ips, $ip);
            $ip=FALSE;
        }
        for ($i=0; $i < count($ips); $i++){
            if(!preg_match ('/^(10│172.16│192.168)./i', $ips[$i])){
                $ip=$ips[$i];
                break;
            }
        }
    }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

/**
 * 递归生成分类树
 * getTree
 * @author: buddha
 * @date 2020/8/1 15:08
 * @param array $item 遍历数组
 * @param int $pid
 * @param string $sub
 * @param int $level
 * @param int $type 获取层级
 * @return array
 */
function getTree($item = [], $type = 3, $pid = 0, $sub = 'children', $level = 1)
{
    $data = [];
    foreach($item as $key => $val){
        if($val['pid'] == $pid && $level <= $type){
            $val['level'] = $level;
            $res = getTree($item, $type, $val['id'], $sub, $level + 1);
            if ($res) {
                $val[$sub] = $res;
            }
            $data[] = $val;
        }
    }
    return $data;
}

/**
 * 生成随机key
 * @param int $length
 * @return bool|string
 */
function randString($length = 6) {
    $str = md5(time());
    $key = substr($str, 3, $length);
    return $key;
}
